package com.easonji.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: FileUtils
 * @Description: 文件操作工具类
 * @Author: LiuJun
 * @date: 2018/07/07 22:05
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
public class FileUtils {

    private final static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 根据文件路径获取文件byte字节
     * 
     * @param filePath
     *            文件路径
     * @return 文件byte字节
     */
    public static byte[] toByteArray(String filename) {
        byte[] result = new byte[0];
        File f = new File(filename);
        if (!f.exists()) {
            logger.error("文件未找到！" + filename);
            return result;
        }
        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
            }
            return byteBuffer.array();
        } catch (IOException e) {
            return result;
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                logger.error("文件读取异常！" + filename);
            }
            try {
                fs.close();
            } catch (IOException e) {
                logger.error("文件读取异常！" + filename);
            }
        }
    }
}
